var registerMainTable;
var groupVisible=true;
$(document).ready(function(){
	if(schoolVisible=="false"){
		groupVisible=false;
	}
	 registerMainTable = $('.table-sort').dataTable(pageStting(groupVisible));
	 $('#DataTables_Table_0_length').find('label').contents().wrap("<span class='f-l mr-10'></span>");
	 if(isManagerPlat=='false'){
		$('#roleGroupName').parent().parent().hide();
		$('#serach_code').parent().parent().style.margin="0 0 0 20%";
	 }else{
//		 $.getJSON(baseURL+'/api/roleGroup/listAll',function(result){
//			 $.each(result.results,function(i,n){
//				 $('#roleGroupId').append("<option value=''>全部</option>") 
//				 $('#roleGroupId').append("<option value='"+n.id+"'>"+n.groupName+"</option>") 
//			 })
//		 })
//		 $('#roleGroupId').next('span').find('input').attr('placeholder','请选择角色组');
		 	$.ajax({
				type:"GET",
				contentType : "application/x-www-form-urlencoded; charset=UTF-8", 
				url:baseURL + '/api/roleGroup/listAll',
				dataType:"JSON",
				success:function(result){
					if(result.flag){
						if(result.results.length!=0){
							$(".pagitionList").empty();
							$.each(result.results,function(i,n){
								$(".pagitionList").append("<li value='"+n.id+"'>"+n.groupName+"</li>")
							})
							$(".pagitionList>li").on('click',function(e){
								e.stopPropagation();
								$("#roleGroupName").val($(e.target).text());
								localStorage.roleId=$(e.target).attr("value");
								$(".pagitionList>li").removeClass("airportSelectBK");
								$(e.target).addClass("airportSelectBK");
							})
						}else {
							$(".pagitionList").empty().append("<li>没有数据</li>")
						}
					}else layer.msg("数据报错："+result.message); 
				}
			  })
			  var isMouse=true;
			  $("#roleGroupName").on('click',function(){
				  $('.pagitionDiv').toggle();
			  })
			$('.pagitionDiv').on('mouseleave',function(e){
				$('.pagitionDiv').hide();
				isMouse=true;
			})
			$('.pagitionDiv').on('mouseover',function(e){
				isMouse=false;
			})
			$('#roleGroupName').on('blur',function(e){
				if(isMouse){
					$(e.target).next().hide();
				}
			})
		 
	 }
	 
	 
	 
	 
	 
});
$(window).resize(function(){
	$(".table-sort").css('width','100%');
});
//从服务器分批取数据
pageStting = function(groupVisible){
		var optsortable = {
					"bPaginate":true,
					"stateSave":true,
					"bProcessing":true,
					"iDisplayLength":10,
					"sAjaxSource":baseURL+'/api/role/list',
					"sPaginationType":'full_numbers',
					"bServerSide": true,
					"bSort": false,             
					"bFilter": false,  
				     "aoColumnDefs": [                 
			                          {               
				                            "render": function (data, type, full){  
				                            	var checkBox = '<input type="checkbox" name="SelectedRoleId"  class="btn btn-danger radius" value="' + full[0]+ '"/>';
												if(roleId == (full[0]+"")){
													checkBox = '<input type="checkbox" name="SelectedRoleId" disabled=true  class="btn btn-danger radius CheckUser" value="' + full[0]+ '"/>';
												}
												return checkBox;
				                              },
				                            "targets": 0 
				                           },
				                          {               
					                            "render": function (data, type, full){  
					                            	if(roleId == (full[0]+"")){
					                            		return ""
					                            	}else{
					                            		var edit_herf ="<div class='text-c handlePointer'><img title='编辑' alt='编辑' src='"+baseURL+"/images/admin/cp_edite.png' onclick=layer_show('600','','编辑','"+baseURL+"/api/role/page/edit/"+full[0]+"?times="+(new Date()).getTime()+"') />"
					        							var trach_herf="<img title='删除' alt='删除' src='"+baseURL+"/images/admin/cp_delete.png' onclick=\"return deleteData('"+full[0]+"')\" /></div>"
					        							return edit_herf + trach_herf;
					                    
					                            	}
					                              },
					                            "targets":5 
					                           }
				                        ] ,
					"fnServerData": function(sSource, aoData, fnCallback){
							var globalSearch = {};
							var searchConditions = {};
							if($.trim($("#serach_code").val())!=''){
								searchConditions.code=$.trim($("#serach_code").val());
							}
							if($.trim($("#roleGroupName").val())!=''&&$.trim($("#roleGroupName").val())!=undefined)
							{
							    searchConditions.roleGroupId=localStorage.roleId;
							}
							globalSearch.name= 'globalSearch';
							globalSearch.value= JSON.stringify(searchConditions);
							aoData.push(globalSearch);
							 $.ajax({  
						        type: "GET",     
						        url: sSource,     
						        dataType: "json",    
						        contentType: "application/json;charset=UTF-8", 
						        data: aoData, // 以json格式传递  
						        success: function(result) {
						        	if(!result.flag){
					            		if(result.statusCode==503){
					            		  location=$('#baseUrl').text()+"/api/tologin";
					            		}else{
					            		  layer.msg("查询失败！");
					            		}
					            	  return;
					            	}
						        	if(result.flag){
							        	var obj =result;
										var data = obj.results;
										var aaData = [];
										var dataResult = {};
										dataResult.iTotalRecords = obj.totalcount;
										dataResult.iTotalDisplayRecords= obj.totalcount;
										dataResult.iDisplayStart = obj.offset;
										dataResult.iDisplayLength= obj.limit;
										dataResult.aaData = aaData;
										//json重构数组对象 
										$.each(data,function(i,val){
											aaData[i]=[]
											aaData[i].push(val.id);
											aaData[i].push(val.name);
											aaData[i].push(val.code);
											aaData[i].push(val.roleGroupName!=null?val.roleGroupName:'/');
											aaData[i].push(val.descn);
											aaData[i].push(val.null_n);
										});
							            fnCallback(dataResult);   
						          }
						        	$('#SelectedRoleId').on('click',function(){
							       		 $.each($("input[name='SelectedRoleId']"),function(i,n){
							       			 if($(n).hasClass('CheckUser')){
							       				 $(n).prop('checked',false);
							       			 }
							       		 })
						       	 	})
						        }    
						     });
					}
				}	
		return optsortable;
}
						
            
		
 deleteData = function(id){
		var data = {};
		data.ids=id;
		layer.confirm('您确定要删除吗？',function(){
			$.ajax({  
		        type: "post",     
		        url: baseURL+'/api/role/delete',     
		        dataType: "json",   
		        contentType: "application/json",
		        data: JSON.stringify(data),
		        success: function(result) {
		        	   if(!result.flag){
		        		   layer.msg("删除失败！原因："+result.message);
		        		   return;
		        	   }else{
		        		   location.reload();
		        	   }
		        }    
		     });
		})
}
			
grant_resource= function(){
	var ids=[];
	var objs = $('input[name="SelectedRoleId"]:checked');
	$.each(objs,function(index,obj){
		var value = $(this).val();
		ids[index] = value;
	});
	 
	if(ids.length==0){
		layer.msg("请选择一个角色！");
		return;
	}
	if(ids.length>1){
		layer.msg("请只选中一个角色！");
		return;
	}
	layer_show('550','','资源授权',baseURL+'/api/role/page/resources/'+ids[0]);
}
		
refreshData = function(){
	ajaxDrawTable();
}
doSearch = function(){
   var seachValue={};
   $('.table-sort').DataTable().search(seachValue).draw();
}	